#include "UserManager.h"
#include "LeagueManager.h"
#include "Team.h"
#include "Utilities.h"
#include "League.h"
#include "User.h"
#include "ZStream.h"

UserManager::UserManager(ServiceProvider* const i_sp)
:m_sp(i_sp)
{
}

UserManager::~UserManager()
{
	Clear();
}

void UserManager::Clear()
{
	Utilities::DeepClear(m_list);
}

void UserManager::AddUser(const STL::string &i_name)
{
	m_list.push_back(new User(m_sp, i_name));
}

UsersList& UserManager::GetUserList()
{
	return m_list;
}

const UsersList& UserManager::GetUserList() const
{
	return m_list;
}

void UserManager::CheckLosingPlayers()
{
	m_gameoverNames.clear();

	const LayerVec& layers = m_sp->GetLeagueMgr().GetAllLayers();
	for(size_t i=0; i< layers.size(); ++i)
	{
		if(layers[i]->GetSettings().isVisible)
			continue;

		const LeagueVec& leagues = layers[i]->GetLeagues();
		for(size_t j=0; j< leagues.size(); ++j)
		{
			const TeamVec& teams = leagues[j]->GetTeams();
			for(size_t k=0; k<teams.size(); ++k)
			{
				UsersListIt deadPlayer = STL::find_if(m_list.begin(), m_list.end(), CompareUserTeamPtr(teams[k]));
				if(deadPlayer != m_list.end())
				{
					m_gameoverNames.push_back((*deadPlayer)->m_name);
					teams[k]->SetUserControlled(false);
					delete *deadPlayer;
					m_list.erase(deadPlayer);
				}
			}
		}
	}
}

ZStream& UserManager::Serialize(ZStream& o_stream) const
{
	o_stream.WriteOpenTag("UserManager");

	o_stream.WriteAttribute("UsersNum", m_list.size());
	for(size_t i = 0; i < m_list.size(); ++i)
		m_list[i]->Serialize(o_stream);

	o_stream.WriteCloseTag("UserManager");

	return o_stream;
}

ZStream& UserManager::Deserialize(ZStream& i_stream)
{
	i_stream.SkipLine();

	size_t usersNum;
	i_stream.ReadAttribute(usersNum);
	m_list.clear();
	for(size_t i = 0; i < usersNum; ++i)
	{
		AddUser("");
		m_list[i]->Deserialize(i_stream);
	}

	i_stream.SkipLine();

	return i_stream;
}
